camera = {};
scene = {};
renderer = {};
controls = {};
catchPoint = {};//临时点集合，异步获取的点都在这
group_line = {};//线组
group_point = {};//点组
group = {};//3d对象组
materialss = {};//材料组
pointMaterial = {};//点材料组
startX = {};//x轴起始值
catchData = {};//缓存最后一个数据点
sss2 = {};//定时器
dataName = {};//原始数据点的名称
dataValue = {};//原始数据点的值
pointGeometry = new THREE.SphereGeometry( 0.2, 32, 16 );//点材料
pointGeometry.sortFacesByMaterialIndex();
//var color = ["#af2300","#00ffaa","#fe96ae","#82f8ce","#f7f58e","#6ecbff","#f8c59d","#d5a2ed","#d16aa2","#70f2f3","#ff66cc"];//颜色组
function pickupObjects(e){
    //将鼠标点击位置的屏幕坐标转成threejs中的标准坐标
     mouse.x = (e.clientX/$("#info").width())*2 -1;
     mouse.y = -(e.clientY/$("#info").height())*2 + 1;
     //从相机发射一条射线，经过鼠标点击位置
     raycaster.setFromCamera(mouse,camera["info"]);
     //计算射线相机到的对象，可能有多个对象，因此返回的是一个数组，按离相机远近排列
     let intersects = raycaster.intersectObjects(group["info"].children);
     console.log("intersects",intersects);
     for ( var i = 0; i < intersects.length; i++ ) {
         //intersects[ i ].object.material.color.set( 0x00ff00 );
     }
}
var my = {
	//canvasdiv : $("#info"),
	//value:[0,2,0,3,4,5,3,2,6,1,5],
	//catchData:{},
	//	value:[null,2,0,null,4,0,3,0],
	//设置相机
	setCamera:function(dom){
		var id = dom[0].id;
		camera[id] = new THREE.PerspectiveCamera( 35, dom.width() / dom.height(), 1, 500 );
		camera[id].up.set( 0, 0, 1 );
		camera[id].position.set( 0, -9, 6 );
		//camera[id].add( new THREE.PointLight( 0xffffff, 0.8 ) );
	},
	//线的截面形状
	getLineShape:function(){
		if(typeof this.shape != "undefined"){
			return this.shape;
		}
		var pts = [], numPts = 2;
		for ( var i = 0; i < numPts * 2; i ++ ) {
			var l = i % 2 == 1 ? 0.2 : 0.2;
			var a = i / numPts * Math.PI+Math.PI/4;
			pts.push( new THREE.Vector2 ( Math.cos( a )*l/2, Math.sin( a )*l ) );
		}
		var shape = new THREE.Shape( pts );
		this.shape = shape;
		return shape;
	},
	//墙体的截面形状
	getWallShape:function(){
		if(typeof this.shape != "undefined"){
			//return this.shape;
		}
		var pts = [], numPts = 2;
		for ( var i = 0; i < numPts * 2; i ++ ) {
			var l = i % 2 == 1 ? 0.1 : 0.1;
			var a = i / numPts * Math.PI+Math.PI/4;
			var y = Math.cos( a )*l;
			console.log(y<0?y*40:0,Math.sin( a )*l+"=");
			pts.push( new THREE.Vector2 ( y<0?y*40:0, Math.sin( a )*l ) );
		}
		var shape = new THREE.Shape( pts );
		//this.shape = shape;
		return shape;
	},
	
	//地板的截面形状
	getFloorShape:function(){
		if(typeof this.shape != "undefined"){
			//return this.shape;
		}
		var pts = [], numPts = 2;
		for ( var i = 0; i < numPts * 2; i ++ ) {
			var l = i % 2 == 1 ? 0.1 : 0.1;
			var a = i / numPts * Math.PI+Math.PI/4;
			var y = Math.sin( a )*l;
			var x = Math.cos( a )*l;
			pts.push( new THREE.Vector2 (x<0?0:x , y<0?0:y*200 ) );
		}
		var shape = new THREE.Shape( pts );
		//this.shape = shape;
		return shape;
	},
	//获取网格辅助线
	getGridArray:function(x1,x2,y){
		var temp = [];
		var material_line = new THREE.LineBasicMaterial({color:"#ff0000",linewidth: 1});
		var material_line2 = new THREE.LineBasicMaterial({color:"#ffffff",linewidth: 1});
		for(var i=x1;i<x2;i++){
			var geom_line = new THREE.Geometry();
			var p1 = new THREE.Vector3(i, -2,0 );
			var p2 = new THREE.Vector3(i, y,0 );
			geom_line.vertices.push.apply(geom_line.vertices, [p1,p2]);
			var line_temp =new THREE.Line(geom_line,material_line);
			if(i%2==0){
					line_temp =new THREE.Line(geom_line,material_line2);
			}
			temp.push(line_temp);
		}
		for(var i=-1;i<y;i++){
			var geom_line = new THREE.Geometry();
			var p1 = new THREE.Vector3(x1, i,0 );
			var p2 = new THREE.Vector3(x2, i,0 );
			geom_line.vertices.push.apply(geom_line.vertices, [p1,p2]);
			var line_temp =new THREE.Line(geom_line,material_line);
			temp.push(line_temp);
		}
		return temp;
	},
	//单个数组数据分割
	splitData:function(source , size){
		var ind =[];
		var data = [];
		for(var i=0;i<source.length;i++){
		  if(source[i][0] != null){
		      ind.push(i);
		      data.push(source[i]);
		  }
		}
		var result = [];
		for(var i=0;i<size*(source.length-1);i++){
		  result[i] = [null,null,null];
		}
		for(var i = 1;i<ind.length;i++){
		  var start = data[i-1];
		  var end = data[i];
		  var num = (ind[i]-ind[i-1])*size;
		  var jg_x = (end[0]-start[0])/num;
		  var jg_y = data[0][1];
		  var jg_z = (end[2]-start[2])/num;
		  for(var j=0;j<num;j++){
				var z_ = start[2]==null?null:start[2] +jg_z*j;
				if(j>0){
				z_ = end[2] == null?null:z_;
				}
				result[ind[i-1]*size+j] = [start[0] +jg_x*j,jg_y,z_];
		  }
		}
		//result[ind[i-1]*size] = data[i-1];
		return result;
	},
	//设置原始数据集
	sourceData:function(id){
		dataName[id] = ["a","b","c","d","e","f","g","h","e","f","g","h","e","f","g","h","g","h","a","b","c","d","e","f","g","h","e","f","g","h","e","f","g","h","g","h"];
		dataValue[id] = {
									s2:[null,2,0,null,4,0,3,0,4,0,3,3,4,0,3,3,3,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3]
									,
									s1:[null,2,2,null,2,2,1,1,4,0,3,3,4,0,3,3,3,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									
									s3:[2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									s4:[1,3,2,1,2,5,1,0,4,0,3,3,4,0,null,3,3,3,2,0,2,1,2,null,1,1,4,0,3,3,4,0,3,3,3,3],
									s5:[2,0,1,1,2,1,1,2,4,0,3,3,4,0,3,3,3,3,2,0,null,1,2,2,1,null,4,0,3,3,4,0,3,3,3,3],
									s31:[2,0,2,1,2,5,1,1,4,0,3,3,4,0,3,null,null,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									s41:[12,3,0,1,2,5,4,0,4,0,3,3,4,0,3,3,3,3,null,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									s51:[2,0,1,12,2,8,1,2,4,0,3,3,4,0,3,3,3,3,2,0,2,null,2,2,1,1,4,0,3,3,4,0,3,3,3,3]
									,
									as1:[null,2,2,null,2,2,1,1,4,0,3,3,4,0,3,3,3,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									as3:[2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									as4:[1,3,2,1,2,5,1,0,4,0,3,3,4,0,null,3,3,3,2,0,2,1,2,null,1,1,4,0,3,3,4,0,3,3,3,3],
									as5:[2,0,1,1,2,1,1,2,4,0,3,3,4,0,3,3,3,3,2,0,null,1,2,2,1,null,4,0,3,3,4,0,3,3,3,3],
									as31:[2,0,2,1,2,5,1,1,4,0,3,3,4,0,3,null,null,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									as41:[12,3,0,1,2,5,4,0,4,0,3,3,4,0,3,3,3,3,null,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									as51:[2,0,1,12,2,8,1,2,4,0,3,3,4,0,3,3,3,3,2,0,2,null,2,2,1,1,4,0,3,3,4,0,3,3,3,3]
									,
									bs1:[null,2,2,null,2,2,1,1,4,0,3,3,4,0,3,3,3,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									bs3:[2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									bs4:[1,3,2,1,2,5,1,0,4,0,3,3,4,0,null,3,3,3,2,0,2,1,2,null,1,1,4,0,3,3,4,0,3,3,3,3],
									bs5:[2,0,1,1,2,1,1,2,4,0,3,3,4,0,3,3,3,3,2,0,null,1,2,2,1,null,4,0,3,3,4,0,3,3,3,3],
									bs31:[2,0,2,1,2,5,1,1,4,0,3,3,4,0,3,null,null,3,2,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									bs41:[12,3,0,1,2,5,4,0,4,0,3,3,4,0,3,3,3,3,null,0,2,1,2,2,1,1,4,0,3,3,4,0,3,3,3,3],
									bs51:[2,0,1,12,2,8,1,2,4,0,3,3,4,0,3,3,3,3,2,0,2,null,2,2,1,1,4,0,3,3,4,0,3,3,3,3]
									};
	},
	//原始数据
	setData:function(start_x,id){
			var points = {};
			var names = dataName[id];
			var value = dataValue[id];
			var color = ["#af2300","#00ffaa","#fe96ae","#82f8ce","#f7f58e","#6ecbff","#f8c59d","#d5a2ed","#d16aa2","#70f2f3","#ff66cc"];//颜色组
			var i = 0;
			for(var p in value){
				var cc = color[i];
				if(cc == null){
					cc = color[i-color.length];
				}
				group_point[id][p] = [];
				var material = new THREE.MeshLambertMaterial( { color: cc, wireframe: false });
				materialss[p] = material;
				pointMaterial[p] = new THREE.MeshLambertMaterial( { color: cc, shading: THREE.FlatShading } )
				i++;
			}		
			var len = names.length;
			var y = 0;
			for(var p in value){
				var arr = value[p];
				points[p] = [];
				for(var i=0;i<len;i++){
					var obj = [i+start_x,y,arr[i]];
					points[p].push(obj);
				}
				y++;
			}						
		return points;
	},
	//数据分割
	setCatchData:function(id){
		var count = 0;
		for(var i=0;i<startX[id].length;i++){
			count += startX[id][i];
		}
		var point = {};
		var data = this.setData(count,id);
		var len = 0;
		for(var p in data){
			len = data[p].length;
			point[p] = my.splitData(data[p],10);	
		}
		startX[id].push(len);
		if(JSON.stringify(catchPoint[id]).length == 2){
			catchPoint[id] = point;
		}else{
			for(var p in point){
				catchPoint[id][p].push.apply(catchPoint[id][p],point[p]);
			}
		}
		
	},
	init : function(dom){
			var id = dom[0].id;

			catchData[id] = null;
			group_line[id] = {};
			catchPoint[id] = {};
			group_point[id] = {};
			startX[id] = [0];
			dataName[id] = {};
			dataValue[id] = {};
			
			init();
	
			function init() {

				scene[id] = new THREE.Scene();
				group[id] = new THREE.Group();
				group[id].position.set.apply(group[id].position,[0,0,0] );
				group[id].add( new THREE.AmbientLight( "#eeeeee") );
				//scene[id].add( new THREE.AmbientLight( "#dd0000") );
				my.setCamera(dom);//设置相机
				scene[id].add( camera[id] );
			
			
			 	var light = new THREE.PointLight( "#555555" );
				light.position.copy( camera[id].position );
				light.position.setZ(5);
				group[id].add( light );
				
				
				var grid = new THREE.GridHelper( 2, 2, "#ffffff", "#ff0000" );
				grid.rotateOnAxis( new THREE.Vector3( 0, 0, 0 ), 90 * ( Math.PI/180 ) );
				group[id].add( grid );//设置网格
				(function(){
						var geometry = new THREE.Geometry();
						var planeSize = 1000;
						for (i = 0; i < 1000; i ++) 
						{ 
						  var vertex = new THREE.Vector3();
						  vertex.x = Math.random()*planeSize-planeSize*.5;
						  vertex.y = Math.random()*planeSize-(planeSize*.5);
						  vertex.z = Math.random()*planeSize-(planeSize*.5);
						  geometry.vertices.push( vertex );
						}
						var material = new THREE.ParticleBasicMaterial( { size: 0.09,color:"#ffffff" });
						var particles = new THREE.ParticleSystem( geometry, material ); 
						scene[id].add( particles ); 
					})();//星空
				
				scene[id].add( group[id] );
				group[id].add.apply(group[id],my.getGridArray(-1,15,20));//网格
				renderer[id] = new THREE.WebGLRenderer( { antialias: true,alpha:true} );
				 renderer[id].setClearColor( "#442255" );
				//renderer[id].setClearAlpha(0);//设置背景图片添加这一行
				 
				 //=========================字体===============================
				 var loader = new THREE.FontLoader(); 
				 loader.load("fonts/gentilis_regular.typeface.json", function (res) {
				  font = new THREE.TextBufferGeometry("equipment", {
					  font: res,
					  size: 0.2,
					  height: 0.02
				  }); 
				  font.computeBoundingBox(); // 运行以后设置font的boundingBox属性对象，如果不运行无法获得。 
				  font.computeVertexNormals(); 
				  var map = new THREE.TextureLoader().load("UV_Grid_Sm.jpg",function(texture){
					  renderer[id].render( scene[id], camera[id] );
				  }); 
//				  var material = new THREE.MeshLambertMaterial({map:map,side:THREE.DoubleSide}); 
				  var material = new THREE.MeshLambertMaterial({side:THREE.DoubleSide}); 
				  fontModel = new THREE.Mesh(font,material); 
				  fontModel.position.set(1,1,1);
				  fontModel.rotation.x = 1.5;
				  group[id].add(fontModel); 
				 }); 
				//===========================墙体========================================
				var pointsa = [new THREE.Vector3(0,10,0),new THREE.Vector3(10,10,0)];
				var randomSplinea =  new THREE.CatmullRomCurve3( pointsa );
			    var geometrya = new THREE.ExtrudeGeometry( my.getWallShape(), {
		        steps			: 2,
		        extrudePath		: randomSplinea
		    	});
			    var materialssa = new THREE.MeshLambertMaterial( { color: "#00ffff", wireframe: false });
				var linea = new THREE.Mesh( geometrya, materialssa );
				group[id].add(linea);
				
				var pointsa = [new THREE.Vector3(10,0,0),new THREE.Vector3(10,10,0)];
				var randomSplinea =  new THREE.CatmullRomCurve3( pointsa );
			    var geometrya = new THREE.ExtrudeGeometry( my.getWallShape(), {
		        steps			: 2,
		        extrudePath		: randomSplinea
		    	});
			    var materialssa = new THREE.MeshLambertMaterial( { color: "#00ffff", wireframe: false });
				var linea = new THREE.Mesh( geometrya, materialssa );
				group[id].add(linea);
				 
				var pointsa = [new THREE.Vector3(0,6,0),new THREE.Vector3(0,10,0)];
				var randomSplinea =  new THREE.CatmullRomCurve3( pointsa );
				var geometrya = new THREE.ExtrudeGeometry( my.getWallShape(), {
					steps			: 2,
					extrudePath		: randomSplinea
				});
				var materialssa = new THREE.MeshLambertMaterial( { color: "#00ffff", wireframe: false });
				var linea = new THREE.Mesh( geometrya, materialssa );
				group[id].add(linea);
				//玻璃
				var pointsa = [new THREE.Vector3(0,0,0),new THREE.Vector3(0,6,0)];
				var randomSplinea =  new THREE.CatmullRomCurve3( pointsa );
				var geometrya = new THREE.ExtrudeGeometry( my.getWallShape(), {
					steps			: 2,
					extrudePath		: randomSplinea
				});
				var materialssa = new THREE.MeshBasicMaterial( { color: "#345612", transparent: true, blending: THREE.AdditiveBlending } );
				var linea = new THREE.Mesh( geometrya, materialssa );
				group[id].add(linea);
				 
				 //========================地板===========================================
				var pointsa = [new THREE.Vector3(-5,-1,0),new THREE.Vector3(15,-1,0)];
				var randomSplinea =  new THREE.CatmullRomCurve3( pointsa );
			    var geometrya = new THREE.ExtrudeGeometry( my.getFloorShape(), {
		        steps			: 2,
		        extrudePath		: randomSplinea
		    	});
			    var materialssa = new THREE.MeshBasicMaterial( { color: "#99aabb", transparent: true, blending: THREE.AdditiveBlending } );
			    
				var linea = new THREE.Mesh( geometrya, materialssa );
				group[id].add(linea);
				
				
				//===============================走线====================================
				
				var geometry_line = new THREE.Geometry();   //声明一个几何体
                var material_line = new THREE.LineBasicMaterial({ color: "#ffff00" });   //定义材质外观
                var p1_line = new THREE.Vector3( 0, 0, 1 );
                var p2_line = new THREE.Vector3( 5, 5, 1 );
                geometry_line.vertices.push(p1_line); //vertices属性里可以存放点对象
                geometry_line.vertices.push(p2_line);
                var line = new THREE.Line(geometry_line, material_line, THREE.LinePieces);    //定义一条线
                group[id].add(line);   //加入场景里
				
                
              //================================立方体贴图===================================
                var materials = [];
                for (var i = 1; i < 5; ++i) {
                    materials.push(new THREE.MeshBasicMaterial({
                        map: THREE.ImageUtils.loadTexture('img/' + i + '.jpg',
                            {}, function() {
                            renderer[id].render( scene[id], camera[id] );
                        }),
                    overdraw: true
                    }));
                }
                var cube = new THREE.Mesh(new THREE.CubeGeometry(2,2,2),new THREE.MeshFaceMaterial(materials));
                cube.aa = {name:"立方体"};
                cube.position.set( 2, 2, 1 );
                group[id].add(cube);
                
                
                
                //=============================场景贴图======================================
                
                
                var urls = [
    						"img/5.jpg",
    						"img/3.jpg",
    						"img/2.jpg",
    						"img/1.jpg",
    						"img/6.jpg",
    						"img/4.jpg",
    					];
            	var path = "img2/";
				var format = '.jpg';
				var urls = [
						path + 'px' + format, path + 'nx' + format,
						path + 'py' + format, path + 'ny' + format,
						path + 'pz' + format, path + 'nz' + format,
					];
            	var reflectionCube = new THREE.CubeTextureLoader().load( urls );
				reflectionCube.format = THREE.RGBFormat;

//				scene = new THREE.Scene();
				scene[id].background = reflectionCube;
				
				
				
                //================================平面贴图===================================
//				var maps = new THREE.TextureLoader().load("aa.jpg",function(texture){
				var maps = new THREE.TextureLoader().load("logo.png",function(texture){
					  renderer[id].render( scene[id], camera[id] );
				  }); 
				
				var geometry = new THREE.PlaneGeometry(1,1);
		        var material = new THREE.MeshBasicMaterial({color:"#ffffff",map:maps,depthTest: false,transparent:true});
		        var rect = new THREE.Mesh(geometry,material);
		        rect.position.set(1,1,0.5);
		        rect.rotation.x = 1.55;
		        group[id].add(rect);
				
				//========================对象拾取===========================================
		        
		        raycaster = new THREE.Raycaster();
		        mouse = new THREE.Vector2();
		        //===================================================================
		        
		        var loadingManager = new THREE.LoadingManager( function() {
		        	group[id].add( elf );
				} );
				var loader = new THREE.ColladaLoader( loadingManager );
				loader.load( 'elf/avatar.dae', function ( collada ) {
//					loader.load( 'elf/elf.dae', function ( collada ) {
					elf = collada.scene;
				} );
                
                
                
				renderer[id].setPixelRatio( window.devicePixelRatio );
				renderer[id].setSize( dom.width(), dom.height());
				dom[0].appendChild( renderer[id].domElement );
				controls[id] = new THREE.OrbitControls( camera[id], renderer[id].domElement );
				controls[id].addEventListener( 'change', render );
				controls[id].target.set( 0, 1.2, 2 );
				controls[id].update();
			}
			function render() {
				renderer[id].render( scene[id], camera[id] );
			}
	},
	//启动定时器
	startInter:function(id){
		sss2[id] = setInterval(function(){
		point = catchPoint[id];
		var the = {};//当前
		for(var p in point){
			the[p] = point[p].shift();
		}
		var last = catchData[id];
		if(catchData[id] != null){//上一个不为空
			for(var p in the){
				var the_v = the[p];
				var last_v = last[p];
				if(the_v[2]!=null&&last_v[2]!=null){
					var points = [new THREE.Vector3(last_v[0],last_v[1],last_v[2]),new THREE.Vector3(the_v[0],the_v[1],last_v[2])];
					var randomSpline =  new THREE.CatmullRomCurve3( points );
			    var geometry = new THREE.ExtrudeGeometry( my.getLineShape(), {
		        steps			: 2,
		        extrudePath		: randomSpline
		    	});
					var line = new THREE.Mesh( geometry, materialss[p] );
					if(typeof group_line[id][p] == "undefined"){
						group_line[id][p] = [];
					}
					//group_line[id][p].push(line);
					//group[id].add(group_line[id][p][group_line[id][p].length-1]);	
					group[id].add(line);			
					if(the_v[0]%1 === 0){//整数点，
						var pp = new THREE.Mesh( pointGeometry, pointMaterial[p] );
						pp.position.set(the_v[0],the_v[1],the_v[2]);
						group_point[id][p].push(pp);
						//group[id].add(group_point[id][p][group_point[id][p].length-1]);
						if(the_v[0]%13 === 0){
							group[id].add.apply(group[id],my.getGridArray(the_v[0]+2,the_v[0]+17,20));//网格	
						}
					}							
				}
			}
		}
		var x_ = group[id].position.x;
		group[id].position.setX(x_-1/10);
		controls[id].update();
		renderer[id].render( scene[id], camera[id] );
		if(JSON.stringify(catchPoint[id]).length == 2){
			clearInterval(sss2[id]);
		}
		for(var p in catchPoint[id]){
			if(catchPoint[id][p] .length == 0){
				clearInterval(sss2[id]);
				break;
			}
		}
		
		catchData[id] = the;
	},100);	
	}
};



//group["info"].remove.apply(group["info"],group_line["info"]["s3"]);
//renderer["info"].render( scene["info"], camera["info"] );


/*

my.sourceData("info");
my.setCatchData("info");
my.startInter("info")
my.sourceData("info2");
my.setCatchData("info2");
my.startInter("info2");

*/